#include "audio_enc_proc.h"
#include "cross_com.h"
#include "imp/imp_audio.h"
CAudioEncProc::CAudioEncProc()
{
	m_pcm_buf = NULL;
	m_aac_buf = NULL;
}

CAudioEncProc::~CAudioEncProc()
{
	if( NULL != m_pcm_buf)
	{
		delete [] m_pcm_buf;
	}

	if(NULL == m_aac_buf)
	{
		delete [] m_aac_buf;
	}
}

int CAudioEncProc::Start()
{
	int ret = 0;
	if(NULL == m_pcm_buf)
	{
		m_pcm_buf = new unsigned char [SIZE_KB(8)];
	}

	if(NULL == m_aac_buf)
	{
		m_aac_buf = new unsigned char[SIZE_KB(4)];
	}

	Cross_CreateThread((cross_start_routine) AudioEncode_THD, (void *)this, NULL,256<<10);

	return 0;
}

int CAudioEncProc::GetFrame(int ch, unsigned char * buf, int buf_size)
{
	int ret = -1;
	int devID = 1;
	int chnID = 0;

//	ret = IMP_AI_PollingFrame(devID, chnID, 1000);
//	if (ret != 0 ) {
//		printf("Audio Polling Frame Data error\n");
//		return -1;
//	}
//
//	IMPAudioFrame frm;
//	ret = IMP_AI_GetFrame(devID, chnID, &frm, BLOCK);
//	if(ret != 0) {
//		printf("Audio Get Frame Data error\n");
//		return -1;
//	}
//
//	*addr = frm.virAddr;
//	*length = frm.len;
//
//	ret = IMP_AI_ReleaseFrame(devID, chnID, &frm);
//	if(ret != 0) {
//		printf("Audio release frame data error\n");
//		return -1;
//	}

	return 0;
}

int CAudioEncProc::AudioEncode_THD(void * arg)
{
	int ret        = -1;
	int devID      = 1;
	int chnID      = 0;
	int drop_ai_f  = 1;
	IMPAudioFrame frm;
	static bool bRun = false;

	if(bRun)
	{
		printf("Audio Record thread is running\n");
		return -1;
	}

	bRun = true;

	ret = IMP_AI_EnableChn(devID, chnID);
	if(ret != 0)
	{
		printf("Audio Record enable channel failed\n");
		goto THD_OUT;
	}

	printf("Start encode audio \n");
	while(true)
	{
		ret = IMP_AI_PollingFrame(devID, chnID, 1000);
		if (ret != 0 )
		{
			printf("Audio Polling Frame Data error\n");
			CrossSleep(100);
			continue;
		}

		ret = IMP_AI_GetFrame(devID, chnID, &frm, BLOCK);
		if(ret != 0)
		{
			printf("Audio Get Frame Data error\n");
			goto THD_OUT;
		}



		ret = IMP_AI_ReleaseFrame(devID, chnID, &frm);
		if(ret != 0) {
			printf("Audio release frame data error\n");
		   continue;
		}

	}

	ret = IMP_AI_DisableChn(devID, chnID);
	if(ret < 0)
	{
		printf("AI_DisableChn fail ret %d.\n",ret);
	}

THD_OUT:
	bRun = false;
	return NULL;

}
